package cn.mesmile.excel.controller;

import ch.qos.logback.core.OutputStreamAppender;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.mesmile.excel.entity.Employee;
import cn.mesmile.excel.entity.User;
import cn.mesmile.excel.service.EmployeeService;
import cn.mesmile.excel.service.UserService;
import com.alibaba.excel.EasyExcel;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zb
 * @date 2020/12/23 10:46
 * @Description
 */
@RequestMapping("/api/v1/excel")
@RestController
public class ExcelController {

    @Autowired
    private UserService userService;

    @Autowired
    private EmployeeService employeeService;

    /**
     *  测试【先删除再添加】
     */
    @GetMapping("/test")
    public String test(){
        List<Employee> employees = new ArrayList<>(10000);
        for (int i = 1; i <= 1000 ; i++) {
            Employee employee = new Employee(i*5, i*10 ,"5");
            employees.add(employee);
        }

        Runnable runnable2 = new Runnable() {
            @Override
            public void run() {
                employeeService.deleteData("");
            }
        };
        Thread thread2 = new Thread(runnable2);
        thread2.start();

        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                employeeService.save(employees);
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();

        return "success";
    }

    @GetMapping("/download")
    public Boolean download() throws Exception {
        // 查询出数据
        List<User> list = userService.list();
        // 新建二进制【输出流】
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // 将Excel写入【输出流】
        EasyExcel.write(outputStream, User.class).sheet("模板").doWrite(list);
        // 将【输出流】写入到【输入流】
        ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());

        String endpoint = "https://oss-cn-chengdu.aliyuncs.com";
        // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
        String accessKeyId =  "LTAI4G6TQi6u8m";
        String accessKeySecret =  "kWIHB5zqfjFgsYf6";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 桶的名称
        String bucketName = "springimage";

        // 注意这个objectName    例如：  upload/test.xlsx  其中 upload 是文件夹，test.xlsx 是文件名
        String objectName = "upload/"+RandomUtil.randomString(6)+".xlsx";
        // 上传文件流。
        PutObjectResult putObjectResult = ossClient.putObject(bucketName, objectName, inputStream);

        // 拼接得出 下载路径
        String urlPath ="https://"+bucketName+".";
        String result = StrUtil.replace(endpoint, "https://", urlPath);
        urlPath = result +"/"+ objectName;

        // 得出下载路径 例如： https://springimage.oss-cn-chengdu.aliyuncs.com/typora/20201216153717.png
        System.out.println("urlPath = " + urlPath);

        // 关闭OSSClient。
        ossClient.shutdown();

        return true;
    }


}
